<script>
export default {
  props: {
    data: {
      type: Object,
      default: () => ({
        markers: [],
        // 默认新加坡
        center: {latitude: 1.3521, longitude: 103.8198}
      })
    },
    isSelect: {
      type: Boolean,
      default: false
    },
    // 可选择的标记数量
    selectCount: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      map: null,
      markersOnMap: [] // 用于存储地图上的标记
    };
  },
  mounted() {
    this.loadGoogleMaps();
  },
  // // 监听data变化
  // watch: {
  //   data: {
  //     handler: function (val) {
  //       // 清除所有markersOnMap
  //       this.markersOnMap.forEach(uuid => {
  //         this.$kt.event.emit(uuid + ":remove");
  //       });
  //       this.markersOnMap = [];
  //       // 重新加载地图
  //       this.initMap()
  //     },
  //     deep: true
  //   }
  // },
  methods: {
    async loadGoogleMaps() {

      if (typeof window.google === 'undefined' || typeof window.google.maps === 'undefined') {
        await new Promise((resolve, reject) => {
          new Promise((resolve, reject) => {
            this.$kt.request.send({
              uri: '/api-google-web/common/getGoogleSecretKey',
              stateSuccess: (res) => {
                const script = document.createElement('script');
                script.src = `https://maps.googleapis.com/maps/api/js?key=${res.data}&language=${this.$i18n.getLanguageCode().replace("_", "-")}`;
                script.async = true;
                script.defer = true;
                script.onload = this.initMap;
                document.head.appendChild(script);
                resolve(res.data);
              },
              stateFail: (err) => {
                reject(err);
              }
            });
          });
        });
      } else {
        this.initMap();
      }
    },
    initMap() {
      const googleMaps = window.google.maps;
      const centerLocation = {
        lat: this.data.center.latitude,
        lng: this.data.center.longitude
      };

      this.map = new googleMaps.Map(this.$refs.mapContainer, {
        center: centerLocation,
        zoom: 8,
      });

      if (this.data.markers && Array.isArray(this.data.markers)) {
        this.data.markers.forEach(markerData => {
          this.addMarker(markerData);
        });
      }

      // 添加地图点击事件监听器
      this.map.addListener('click', (event) => {
        if (this.isSelect) {
          const newMarker = {
            latitude: event.latLng.lat(),
            longitude: event.latLng.lng()
          };
          this.addMarker(newMarker);
          this.data.markers.push(newMarker); // 更新传入的数据
          setTimeout(() => {
            this.$emit('select', this.data.markers); // 触发事件
          }, 500);
        }
      });
    },
    addMarker(markerData) {
      const googleMaps = window.google.maps;
      const markerLocation = {
        lat: markerData.latitude,
        lng: markerData.longitude
      };

      const marker = new googleMaps.Marker({
        position: markerLocation,
        map: this.map,
        title: this.isSelect ? null : (markerData.title || '.'),
        label: {
          text: this.isSelect ? null : (markerData.title || '.'),
          fontSize: '12px',
          fontWeight: 'bold',
        }
      });

      // 创建 InfoWindow 实例
      const infoWindow = new googleMaps.InfoWindow({
        content: `<div style="text-align: center;">${markerData.title || 'Marker'}</div>`
      });

      // 默认显示 InfoWindow
      // infoWindow.open(this.map, marker);


      // // 创建 InfoWindow 实例
      // const infoWindow = new googleMaps.InfoWindow({
      //   content: markerData.title || 'Marker'
      // });
      //
      // // 默认显示 InfoWindow
      // infoWindow.open(this.map, marker);

      // 添加右键点击事件，删除标记
      marker.addListener('click', () => {
        if (!this.isSelect) {
          // 打开弹窗
          infoWindow.open(this.map, marker);
          return;
        }
        marker.setMap(null); // 移除标记
        // 从 markers 数组中移除对应的标记
        this.data.markers = this.data.markers.filter(m => m.latitude !== markerData.latitude || m.longitude !== markerData.longitude);

      });

      // uuid
      let uuid = this.$kt.util.generateUUID();
      // 监听uuid
      this.$kt.event.on(uuid + ":remove", () => {
        marker.setMap(null); // 移除标记
        // 从 markers 数组中移除对应的标记
        this.data.markers = this.data.markers.filter(m => m.latitude !== markerData.latitude || m.longitude !== markerData.longitude);
        // 清除监听
        this.$kt.event.off(uuid + ":remove");
      });

      // 存储到 markersOnMap 数组中
      this.markersOnMap.push(uuid);

      // if (this.data.markers.length >= this.selectCount) {
      //   // this.$kt.event.emit(this.markersOnMap[0]+":remove");
      //   // // 删除第一个
      //   // this.markersOnMap.shift();
      //   // // 删除markers
      //   // this.data.markers.shift();
      //   // 保留最后this.selectCount个
      //   let removeCount = this.data.markers.length - this.selectCount;
      //   for (let i = 0; i < removeCount; i++) {
      //     this.$kt.event.emit(this.markersOnMap[i] + ":remove");
      //     // 删除第一个
      //     this.markersOnMap.shift();
      //     // 删除markers
      //     this.data.markers.shift();
      //     console.log(JSON.stringify(this.data.markers));
      //   }
      // }
      //
      // 获取markerOnMap的长度
      console.log(this.markersOnMap.length);
      if (this.markersOnMap.length > this.selectCount && this.isSelect) {
        // 删除第一个
        this.$kt.event.emit(this.markersOnMap[0] + ":remove");
        // 删除第一个
        this.markersOnMap.shift();
        // 删除markers
        this.data.markers.shift();
        console.log(JSON.stringify(this.data.markers));
      }


    }
  }
}
</script>

<template>
  <div ref="mapContainer" style="width: 100%; height: 100%;"></div>
</template>

<style scoped lang="scss">
</style>
